//插件加载
import plugin from '../../../lib/plugins/plugin.js'
import data from '../model/XiuxianData.js'
import config from "../model/Config.js"
import fs from "fs"
import { segment } from "oicq"
import { Read_player, existplayer, set_log } from './xiuxian.js'
import { Add_灵石 } from './xiuxian.js'
import { __PATH } from "./xiuxian.js"

/**
 * 全局变量
 */

let allaction = false;//全局状态判断
/**
 * 货币与物品操作模块
 */

export class MoneyOperation extends plugin {
    constructor() {
        super({
            name: 'MoneyOperation',
            dsc: '修仙模块',
            event: 'message',
            priority: 600,
            rule: [
                {
                    reg: '^(孝敬前辈|资助后辈|赠送灵石).*$',
                    fnc: 'Give_lingshi'
                },
                {
                    reg: '^#发红包.*$',
                    fnc: 'Give_honbao'
                },
                {
                    reg: '^#抢红包$',
                    fnc: 'uer_honbao'
                },
                {
                    reg: '^#发福利.*$',
                    fnc: 'Allfuli'
                },
                {
                    reg: '^#发补偿.*$',
                    fnc: 'Fuli'
                },
                {
                    reg: '^#打开钱包$',
                    fnc: 'openwallet'
                }
            ]
        })
        this.xiuxianConfigData = config.getConfig("xiuxian", "xiuxian");
    }


    async Give_lingshi(e) {
        //这是自己的
        let A_qq = e.user_id;
        //自己没存档
        let ifexistplay = await existplayer(A_qq);
        if (!ifexistplay) { return; }
        //全局状态判断
        await Go(e);
        if (allaction) {
            console.log(allaction);
        }
        else {
            return;
        }
        allaction = false;

        //对方
        let isat = e.message.some((item) => item.type === "at");
        if (!isat) {
            return;
        }
        let atItem = e.message.filter((item) => item.type === "at");//获取at信息
        let B_qq = atItem[0].qq;//对方qq
        //对方没存档
        ifexistplay = await existplayer(B_qq);
        if (!ifexistplay) { e.reply(`此人尚未踏入仙途`); return; }

        //获取发送灵石数量
        let lingshi = e.msg.replace("#", "");
        lingshi = lingshi.replace("孝敬前辈", "");
        lingshi = lingshi.replace("资助后辈", "");
        lingshi = lingshi.replace("赠送灵石", "");


        //校验输入灵石数
        if (parseInt(lingshi) == parseInt(lingshi) && parseInt(lingshi) >= 1000) {
            lingshi = parseInt(lingshi);
        }
        else {
            e.reply(`这么点灵石你也好拿得出手吗?起码要1000灵石,已为您修改`);
            lingshi = 1000;
        }//没有输入正确数字或＜1000;
        //检验A有没有那么多灵石
        let A_player = await data.getData("player", A_qq);

        let B_player = await data.getData("player", B_qq);

        if (A_player.灵石 < lingshi) {
            e.reply([segment.at(A_qq), `你身上似乎没有${lingshi}灵石`]);
            return;
        }

        let now = new Date();
        let nowTime = now.getTime(); //获取当前时间戳
        let lastgetbung_time = await redis.get("xiuxian:player:" + A_qq + ":last_getbung_time");
        lastgetbung_time = parseInt(lastgetbung_time);
        let transferTimeout = parseInt(this.xiuxianConfigData.CD.transfer * 60000)
        if (nowTime < lastgetbung_time + transferTimeout) {
            let waittime_m = Math.trunc((lastgetbung_time + transferTimeout - nowTime) / 60 / 1000);
            let waittime_s = Math.trunc(((lastgetbung_time + transferTimeout - nowTime) % 60000) / 1000);
            e.reply(`每${transferTimeout / 1000 / 60}分钟赠送灵石一次，正在CD中，` + `剩余cd: ${waittime_m}分${waittime_s}秒`);
            return;
        }

        var cost = this.xiuxianConfigData.percentage.cost;
        //交易
        await Add_灵石(A_qq, -lingshi);
        let lastlingshi = Math.trunc(lingshi * cost);
        await Add_灵石(B_qq, lastlingshi);
        e.reply([segment.at(A_qq), segment.at(B_qq), `${B_player.名号} 获得了由 ${A_player.名号}赠送的${lingshi}灵石`])
        //记录本次获得赠送灵石的时间戳
        await redis.set("xiuxian:player:" + A_qq + ":last_getbung_time", nowTime);
        return;
    }


    //发福利
    async Give_honbao(e) {
        //这是自己的
        let usr_qq = e.user_id;
        //自己没存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) { return; }
        //全局状态判断
        await Go(e);
        if (allaction) {
            console.log(allaction);
        }
        else {
            return;
        }
        allaction = false;

        //获取发送灵石数量
        let lingshi = e.msg.replace("#", "");
        lingshi = lingshi.replace("发红包", "");

        let player = await data.getData("player", usr_qq);

        //对比自己的灵石，看看够不够！
        if (player.灵石 <= parseInt(lingshi)) {
            e.reply(`红包数要比自身灵石数小噢`);
            return;
        }

        let getlingshi = 0;

        //循环取整
        for (var i = 1; i <= 200; i++) {
            //校验输入灵石数
            if (parseInt(lingshi) == parseInt(lingshi) && parseInt(lingshi) == i * 10000) {
                //按万算，最高送百万灵石
                //符合调节就进来
                getlingshi = parseInt(lingshi);
                break;
            }
        }

        //取完之后查看灵石是否为零
        if (lingshi != getlingshi) {
            //不符合的，返回，并提示玩家
            e.reply(`最低红包为一万灵石噢，并且必须是万的倍数，最高可发两百万`);
            return;
        }

        //发送的灵石要当到数据库里。大家都能取
        await redis.set("xiuxian:player:" + usr_qq + ":honbao", lingshi);
        //然后扣灵石
        await Add_灵石(usr_qq, -lingshi);
        e.reply("【全服公告】" + player.名号 + "发了个" + lingshi + "灵石的红包！");
        return;
    }


    //抢红包
    async uer_honbao(e) {
        let usr_qq = e.user_id;

        //自己没存档
        let ifexistplay = await existplayer(usr_qq);
        if (!ifexistplay) {
            return;
        }

        let player = await data.getData("player", usr_qq);

        //抢红包要有一分钟的CD
        let now_time = new Date().getTime();
        let lastgetbung_time = await redis.get("xiuxian:player:" + usr_qq + ":last_getbung_time");
        lastgetbung_time = parseInt(lastgetbung_time);
        let transferTimeout = parseInt(this.xiuxianConfigData.CD.honbao * 60000)
        if (now_time < lastgetbung_time + transferTimeout) {
            let waittime_m = Math.trunc((lastgetbung_time + transferTimeout - now_time) / 60 / 1000);
            let waittime_s = Math.trunc(((lastgetbung_time + transferTimeout - now_time) % 60000) / 1000);
            e.reply(`每${transferTimeout / 1000 / 60}分钟抢一次，正在CD中，` + `剩余cd: ${waittime_m}分${waittime_s}秒`);
            return;
        }

        //要艾特对方，表示抢对方红包
        let isat = e.message.some((item) => item.type === "at");
        if (!isat) {
            return;
        }

        let atItem = e.message.filter((item) => item.type === "at");
        let honbao_qq = atItem[0].qq;
        //有无存档
        let ifexistplay_honbao = await existplayer(honbao_qq);
        if (!ifexistplay_honbao) {
            return;
        }

        //先查看里面还有多少灵石
        var lingshi = await redis.get("xiuxian:player:" + honbao_qq + ":honbao");
        if (lingshi <= 1000) {
            e.reply("他的红包被光啦！");
            return;
        }


        var addlingshi = 0;
        //当然谨防意外
        if (lingshi >= 100) {
            //要取整
            addlingshi = lingshi / 10;
            addlingshi = Math.trunc(addlingshi);
            //要取
            lingshi = lingshi - addlingshi;
            lingshi = Math.trunc(lingshi);

        }

        //或者说，自己抢到了。不够100了、就抢不了。
        if (addlingshi <= 100) {
            e.reply("他的红包被光啦！");
            return;
        }

        //重新存起来
        await redis.set("xiuxian:player:" + honbao_qq + ":honbao", lingshi);
        //拿出来的要给玩家
        await Add_灵石(usr_qq, addlingshi);
        //给个提示
        e.reply("【全服公告】" + player.名号 + "抢到一个" + addlingshi + "灵石的红包！");
        //记录时间
        await redis.set("xiuxian:player:" + usr_qq + ":last_getbung_time", now_time);
        return;
    }


    //发福利
    async Allfuli(e) {
        if (!e.isMaster) {
            e.reply("只有主人可以执行操作");
            return;
        }

        //获取发送灵石数量
        let lingshi = e.msg.replace("#", "");
        lingshi = lingshi.replace("发", "");
        lingshi = lingshi.replace("福利", "");

        //校验输入灵石数
        if (parseInt(lingshi) == parseInt(lingshi) && parseInt(lingshi) > 0) {
            lingshi = parseInt(lingshi);
        }
        else {
            lingshi = 100;//没有输入正确数字或不是正数
        }

        let File = fs.readdirSync(__PATH.player_path);
        File = File.filter(file => file.endsWith(".json"));
        let File_length = File.length;
        for (var i = 0; i < File_length; i++) {
            let this_qq = File[i].replace(".json", '');
            await Add_灵石(this_qq, lingshi);
        }

        e.reply(`福利发放成功,目前共有${File_length}个玩家,每人增加${lingshi}灵石`);
        return;
    }




    //发补偿
    async Fuli(e) {
        if (!e.isMaster) {
            e.reply("只有主人可以执行操作");
            return;
        }
        //获取发送灵石数量
        let lingshi = e.msg.replace("#", "");
        lingshi = lingshi.replace("发", "");
        lingshi = lingshi.replace("补偿", "");

        //校验输入灵石数
        if (parseInt(lingshi) == parseInt(lingshi) && parseInt(lingshi) > 0) {
            lingshi = parseInt(lingshi);
        }
        else {
            lingshi = 100;//没有输入正确数字或不是正数
        }

        let isat = e.message.some((item) => item.type === "at");
        if (!isat) {
            return;
        }
        let atItem = e.message.filter((item) => item.type === "at");
        let this_qq = atItem[0].qq;
        //有无存档
        let ifexistplay = await existplayer(this_qq);
        if (!ifexistplay) {
            e.reply(`此人尚未踏入仙途`);
            return;
        }
        let player = await data.getData("player", this_qq);
        await Add_灵石(this_qq, lingshi);
        e.reply(`【全服公告】 ${player.名号} 获得${lingshi}灵石的补偿`);
        return;
    }


    async openwallet(e) {
        

        e.reply("待实装！");


    }



}



/**
 * 状态
 */

export async function Go(e) {
    let usr_qq = e.user_id;
    //有无存档
    let ifexistplay = await existplayer(usr_qq);
    if (!ifexistplay) {
        return;
    }
    //获取游戏状态
    let game_action = await redis.get("xiuxian:player:" + usr_qq + ":game_action");
    //防止继续其他娱乐行为
    if (game_action == 0) {
        e.reply("修仙：游戏进行中...");
        return;
    }
    //查询redis中的人物动作
    let action = await redis.get("xiuxian:player:" + usr_qq + ":action");
    action = JSON.parse(action);
    if (action != null) {
        //人物有动作查询动作结束时间
        let action_end_time = action.end_time;
        let now_time = new Date().getTime();
        if (now_time <= action_end_time) {
            let m = parseInt((action_end_time - now_time) / 1000 / 60);
            let s = parseInt(((action_end_time - now_time) - m * 60 * 1000) / 1000);
            e.reply("正在" + action.action + "中,剩余时间:" + m + "分" + s + "秒");
            return;
        }
    }
    let player = await Read_player(usr_qq);
    if (player.当前血量 < 200) {
        e.reply("你都伤成这样了,就不要出去浪了");
        return;
    }
    allaction = true;
    return;
}